package com.my.socket.nio.v32;

import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by ZhongGang
 * at 2018/8/24 15:45
 */
public class Poller implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(Poller.class);

    private Selector selector;

    public Poller(Selector selector) {
        this.selector = selector;
    }

    @Override
    public void run() {
        while (!Thread.interrupted()) {
            try {
                int select = this.selector.select(10);
                if (select > 0) {
                    Set<SelectionKey> selectionKeys = this.selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();
                        iterator.remove();

                        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        socketChannel.read(readBuffer);
                        String request = new String(readBuffer.array());
                        LOGGER.info("read: {}", request);

                        String response = request.toUpperCase();
                        ByteBuffer writeBuffer = ByteBuffer.wrap(response.getBytes());
                        socketChannel.write(writeBuffer);
                        LOGGER.info("write: {}", response);

                        socketChannel.close();
                    }
                }
            } catch (Exception e) {
                LOGGER.error("exception caught, the error is {}", Throwables.getStackTraceAsString(e));
            }
        }
    }
}
